﻿using Models.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace GateWayCloodService.Device
{

    public static class ServiceDeviceJiDianQICommandByWifi
    {

        //服务端buffer为4字节
        static byte[] buffer = new byte[1024];
        private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);
        public static List<ReceiveCallbackModel> receiveCallbackModels = new List<ReceiveCallbackModel>();
        //public static bool sendAndReceiveToServer(MQReqModel<CommandLogModel> mQReqModel)
        //{
        //    TimeoutObject.Reset();
        //    Socket socket;
        //    //定义主机的IP及端口
        //    IPAddress iPAddress = IPAddress.Parse(mQReqModel.data.local_ip);
        //    IPEndPoint ipEnd = new IPEndPoint(iPAddress, int.Parse(mQReqModel.data.local_port));
        //    //定义套接字类型
        //    socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //    //尝试连接
        //    try
        //    {

        //        socket.SendTimeout = 2000;//不起作用
        //        socket.ReceiveTimeout = 2000;//不起作用
        //        socket.ConnectAsync(ipEnd);//异步，，不然如果是 连接超时，要等130秒左右
        //        //阻塞当前线程,使其等待异步连接,如果在指定时间内
        //        if (!TimeoutObject.WaitOne(800, false))
        //        {//2秒中断
        //            if (!socket.Connected)
        //            {


        //                //MQReqModel<CommandLogModel> mQReqModel = new MQReqModel<CommandLogModel>();
        //                mQReqModel.respEvent = MQEventEnum.Device_Jidianqi;
        //                mQReqModel.respCode = "3";
        //                mQReqModel.respMsg = "socket连接失败";
        //                //mQReqModel.gateWayId = UtilsMachineInfo.getMachineId();
        //                //mQReqModel.data = commandLogModel; ;
        //                // mQReqModel.guid = System.Guid.NewGuid().ToString();
        //                new ServiceRabbitMQ_DeviceHelper().sendMsg(JsonConvert.SerializeObject(mQReqModel));


        //                ////请求接口
        //                //HttpHelper http = new HttpHelper();
        //                ////返回异常
        //                //var jsonuser = http.sendPostRequest(appsettingHelper.GetSettings("base:updateWorkUrl"), "guid=" + guid + "&status=3&msg=socket连接失败");

        //                //FileHelper.deviceServer_WriteMessageAppend(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").ToString() + " wifi继电器"+ ip + "连接超时");
        //                return false;//连接中断
        //            }
        //            else
        //            {
        //                sendCommand(socket, mQReqModel.data.content);
        //            }
        //        }

        //        ReceiveCallbackModel receiveCallbackModel = new ReceiveCallbackModel();
        //        receiveCallbackModel.ReceiveSocket = socket;
        //        receiveCallbackModel.guid = mQReqModel.data.guid.ToString();
        //        receiveCallbackModel.ReceiveTime = DateTime.Now;
        //        socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), receiveCallbackModel);
        //        return true;
        //    }
        //    //异常处理
        //    catch (Exception ee)
        //    {
        //        throw ee;
        //        //  throw ee;
        //        //  return;
        //    }
        //}
        public static void sendCommand(Socket socket, string sendMsg)
        {
            //定义发送数据缓存
            byte[] data = new byte[1024];
            //定义字符串，用于控制台输出或输入
            // string stringData;
            //定义接收数据的长度
            //int recv = socket.Receive(data);
            //将接收的数据转换成字符串
            // stringData = Encoding.ASCII.GetString(data, 0, recv);
            //控制台输出接收到的数据
            //textBox1.Text += "\r\n" + stringData;

            //定义从键盘接收到的字符串
            //input = "00 00 00 00 00 09 01 10 00 00 00 01 02 01 00";// Console.ReadLine();

            //将从键盘获取的字符串转换成整型数据并存储在数组中    
            data = HexStrTobyte(sendMsg);
            //发送该数组
            socket.Send(data, data.Length, SocketFlags.None);

            // socket.Close();
            //return stringData;
        }
        static void ReceiveCallback(IAsyncResult result)
        {
            ReceiveCallbackModel receiveCallbackModel = (ReceiveCallbackModel)result.AsyncState;
            Socket ts = receiveCallbackModel.ReceiveSocket;
            int buffLen = ts.EndReceive(result);
            result.AsyncWaitHandle.Close();
            if (buffLen > 0)
            {
                string str = byteToHexStr(buffer, buffLen);// Encoding.ASCII.GetString(buffer, 0, buffLen);
                Console.WriteLine("收到消息：{0}", str);
                receiveCallbackModel.ReceiveContent = str;
                receiveCallbackModels.Add(receiveCallbackModel);
            }
            ts.Close();
            ts.Dispose();
            //清空缓存数据
            ReceiveCallbackModelClear();
        }

        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes, int byteslength)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < byteslength; i++)
                {
                    returnStr += bytes[i].ToString("X2") + " ";
                }
            }
            return returnStr;
        }
        public static byte[] HexStrTobyte(string hexString)
        {

            hexString = hexString.Replace(" ", "");

            if (hexString.Length % 2 != 0)

                hexString += "";

            byte[] returnBytes = new byte[hexString.Length / 2];

            for (int i = 0; i < returnBytes.Length; i++)
            {
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
            }
            return returnBytes;

        }
        /// <summary>
        /// 删除没用的缓存，5分钟前的
        /// </summary>
        public static void ReceiveCallbackModelClear()
        {
            List<ReceiveCallbackModel> receiveCallbackModelClear = receiveCallbackModels.Where(c => c.ReceiveTime < DateTime.Now.AddMinutes(-5)).ToList();
            foreach (ReceiveCallbackModel item in receiveCallbackModelClear)
            {
                receiveCallbackModels.Remove(item);
            }
        }
    }
}
